<script setup lang="ts">
import router from "@/router";
import {reactive} from "vue";
import request from "@/utils/request.ts";
import {useRouter} from "vue-router";
import {ElDialog, ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  value: '储物柜',
  location: '',
  classification: '',
  currentActive:'',
  menuItems: [
    { index: "/allgoods", name: '所有' },
    { index: "/bedroom", name: '卧室' },    // Changed to path format for consistency
    { index: "/studyroom", name: '书房' },  // Changed to path format
    { index: "/kitchen", name: '厨房' },
    { index: "/livingroom", name: '客厅' },
    { index: "/diningroom", name: '餐厅' },
    { index: "/toilet", name: '卫生间' },
    { index: "/bathroom", name: '浴室' },
    { index: "/balcony", name: '阳台' },
    { index: "/storageroom", name: '储物间' },
    { index: "/cloakroom", name: '衣帽间' }  // Fixed duplicate index issue
  ],
  options: [
    {
      value: '/',
      label: '储物柜',
    },
    {
      value: '/person',
      label: '用户中心',
    },
  ],
  tipGoods:[],
  goodList:[],
  pageNum: 1,        // 当前页码（默认第一页）
  pageSize: 6,      // 每页条数（默认10条）
  total: 0,
  user: JSON.parse(localStorage.getItem("code_user") ||"{}"),
  formVisible: false,
})
// 核心：分类搜索函数
// const handleSearch = () => {
//   // 1. 校验：避免空搜索
//   const keyword = classification.value.trim();
//   if (!keyword) {
//     ElMessage.warning("请输入分类关键词（如：常用）");
//     return;
//   }
//   // 2. 跳转到物品列表页（确保结果在正确页面展示）
//   router.push("/goods"); // 假设列表页路由为 /allgoods
//   // 3. 发送全局事件：将关键词传递给列表页（跨组件通信）
//   window.dispatchEvent(
//       new CustomEvent("searchByClassification", {
//         //detail: keyword, // 传递去空格后的关键词
//         detail:{
//           keyword:keyword,
//           type: 1
//         }
//       })
//   );
//   // 4. 清空搜索框（优化用户体验）
//   classification.value = "";
// }
function load() {
  data.currentActive='/allgoods'
  clickSearch('所有')
  tip()
}
function tip() {
  request.get("/tipGoods",{
    params:{
      userid:data.user.userid
    }
  }).then(res => {
    // console.log(res)
    if (res.data && res.data.length > 0) {
      data.tipGoods = res.data;
      data.formVisible = true;
    }
  }).catch(error => {
    console.error("紧急物品查询失败：", error);
  });
}
load()
function reset(){
  data.classification = "";
}
function search(){
  request.get("/goods", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      location: data.location,
      classification: data.classification,
      userid: data.user.userid,
    }
  }).then(res => {
    // console.log(res)
    data.goodList = res.data.list
    data.total = res.data.total
  }).catch(error => {
    console.error("goods查询错误");
  });
}
function clickSearch(location: string) {
  if (location == "所有")
  {
    location = ''
  }
  data.location = location // 更新选中的位置
  search()
  // window.dispatchEvent(
  //     new CustomEvent("searchByClassification", {
  //       //detail: keyword, // 传递去空格后的关键词
  //       detail:{
  //         keyword:location,
  //         type: 2
  //       }
  //     })
  // );
}
function inputSearch() {
  search()
}
// Vue3 路由设置
function setup() {
  const router = useRouter()
  return { router }
}
function selectoption() {
  if (data.value) {
    router.push(data.value)
  }
}

</script>
<template>
    <div class="body">
      <el-dialog
          v-model="data.formVisible"
          width="500px"
          destroy-on-close
          title="紧急物品提醒"

      >
        <div class="dialog-content">
          <div
              v-for="(item, index) in data.tipGoods"
              :key="item.goodsid || index"
              class="goods-item"
          >
            <el-form label-width="80px" style="width: 100%;">
              <el-form-item label="名称">
                <el-text>{{ item.name}}</el-text>
              </el-form-item>
              <el-form-item label="数量">
                <el-text>{{ item.number}} 件</el-text>
              </el-form-item>
              <el-form-item label="位置">
                <el-text>{{ item.location}}</el-text>
              </el-form-item>
              <el-form-item label="到期时间">
                <el-text>{{'两天后' }}</el-text>
              </el-form-item>
            </el-form>
            <div class="divider" v-if="index !== data.tipGoods.length - 1"></div>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="data.formVisible = false">知道了</el-button>
          </div>
        </template>
      </el-dialog>
      <el-menu
            :default-active="data.currentActive"
            class="el-menu-vertical-demo"
        >
        <el-menu-item>
          <h1>所属区域</h1>
        </el-menu-item>
          <el-menu-item
              v-for="item in data.menuItems"
              :key="item.index"
              :index="item.index.toString()"
              :class="{ 'menu-item': true }"
              @click="clickSearch(item.name)"
          >
            <span slot="title">{{ item.name }}</span>
          </el-menu-item>
        </el-menu>
    <div class="main-card">
      <div class="main-header">
        <div class="main-search">
        <el-input
            v-model="data.classification"
            style="width: 400px; height: 40px"
            placeholder="请输入物品名称/分类查询"
            prefix-icon="Search"
            @keyup.enter="inputSearch"
        />
        <!--      // 支持回车键触发搜索-->
        <el-button type="primary" plain style="height: 40px; margin-left: 10px" @click="clickSearch">搜索</el-button>
        <el-button type="primary" plain style="height: 40px; margin-left: 10px" @click="reset">重置</el-button>
      </div>
        <div class="main-menu">
          <el-select
            v-model="data.value"
            @change="selectoption"
        >
          <el-option
              v-for="item in data.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </div>
      </div>
      <router-view :goodList="data.goodList" @refreshGoods="search" />
      <div class="card">
          <el-pagination
              v-model:current-page="data.pageNum"
              v-model:page-size="data.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[6,12]"
              :total="data.total"
              @current-change="search"
              @size-change="search"
          />
        </div>
  </div>
  </div>
</template>
<style scoped>
.body{
  min-height: 100vh;
  background-image: url("../assets/images/bg_g.jpg");
  background-size: cover;
}
.el-menu-vertical-demo{
  position: fixed;
  height: 100%;
  width: 250px;
  background-color: rgba(255, 255, 254, 0.71);
}
/* 默认选中项样式 */
.el-menu-item.is-active {
  background-color: rgba(169, 156, 156, 0.19) !important;
  border-left: 3px solid #c2083b !important;
}
/* 选中项文字样式 */
.el-menu-item.is-active span {
  color: #c72727 !important;
  font-weight: 900;
}
/* 悬停效果 */
.el-menu-item:not(.is-active):hover {
  background-color: rgba(230, 210, 218, 0.29) !important;
}
.el-menu-item:not(.is-active):hover span {
  color: #dc0a29;
}
.main-card {
  display: flex;
  flex:1;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-left: 250px;
}
.main-header {
  display: flex;
  flex-direction: row;
  margin-top: 20px;
  position: relative;
}
.main-search{
  display: flex;
}
.main-menu{
  display: flex;
  flex: 1;
  width: 100px;
  margin-left: 40px;
}
.card{
  display: flex;
  flex-direction: column;
  position: fixed;
  align-items: center;
  bottom: 10px;
  width:70%;
}
</style>
